/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.tordroid.ui;

import android.app.Fragment;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.Spannable;
import android.text.TextWatcher;
import android.text.style.StyleSpan;
import android.view.*;
import android.widget.*;
import de.tordroid.R;
import de.tordroid.core.Database;
import de.tordroid.core.Engine;
import de.tordroid.core.adapter.IconSpinnerAdapter;
import de.tordroid.model.CharacterClass;
import de.tordroid.model.Faction;

/**
 *
 * @author Christian Simon
 */
public class CharacterFragment extends Fragment {

    private IconSpinnerAdapter raceAdapter;
    private IconSpinnerAdapter classAdapter;
    private IconSpinnerAdapter factionAdapter;
    private Spinner raceSpinner;
    private Spinner factionSpinner;
    private Spinner classSpinner;
    private CheckBox availabilityBox;
    private EditText edit_name;
    private EditText edit_legacy;
    private EditText edit_background;
    private TextView text_fullname; // Contains content(edit_name + " " + edit_legacy)
    private ImageView img_availability;
    private NumberPicker np_age;
    //private EditText edit_age;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onPause()
    {
        super.onPause();
        Database.save();
    }
    
    public static CharacterFragment newInstance() {
        CharacterFragment f = new CharacterFragment();
        return f;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initUI();
        updateContent();
        initListener();
        initSpinner(); 
    }

    private void initUI() {
        // Prepare UI Elements
        text_fullname = (TextView) getActivity().findViewById(R.id.character_fragment_name);
        raceSpinner = (Spinner) getActivity().findViewById(R.id.character_fragment_race);
        factionSpinner = (Spinner) getActivity().findViewById(R.id.character_fragment_faction);
        classSpinner = (Spinner) getActivity().findViewById(R.id.character_fragment_class);

        raceAdapter = new IconSpinnerAdapter(Engine.getRaces(), getActivity());
        classAdapter = new IconSpinnerAdapter(Engine.getClasses(Engine.getCharacterFaction()), getActivity());
        factionAdapter = new IconSpinnerAdapter(Engine.getFactions(), getActivity());

        edit_name = (EditText) getActivity().findViewById(R.id.character_fragment_name_edit);
        edit_legacy = (EditText) getActivity().findViewById(R.id.character_fragment_legacy_edit);
        edit_background = (EditText) getActivity().findViewById(R.id.character_fragment_background);
        np_age = (NumberPicker) getActivity().findViewById(R.id.character_fragment_age);
        np_age.setMaxValue(255);
        np_age.setMinValue(1);
        
        
        img_availability = (ImageView) getActivity().findViewById(R.id.character_fragment_icon_availability);
        availabilityBox = (CheckBox) getActivity().findViewById(R.id.character_fragment_availability);
    }

    private void updateContent() {
        // Manipulate simple UI Elements
        text_fullname.setText(Engine.getCharacterFullname());
        edit_name.setText(Engine.getCharacterSurname());
        edit_legacy.setText(Engine.getCharacterLastname());
        availabilityBox.setChecked(Engine.getCurrentCharacter().isAvailable());
        img_availability.setImageResource(Engine.getAvailabilityIcon(Engine.getCurrentCharacter()));
        edit_background.setText(Html.fromHtml(Engine.getCharacterBackground()));
        np_age.setValue(Engine.getCharacterAge());
    }

    private void initListener() {
        np_age.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {

            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                Engine.setCharacterAge(newVal);
            }
        });

        availabilityBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Engine.setCharacterAvailablility(isChecked);
                img_availability.setImageResource(Engine.getAvailabilityIcon(Engine.getCurrentCharacter()));
            }
        });

        edit_name.addTextChangedListener(new TextWatcher() {

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            public void afterTextChanged(Editable s) {
                // Validate against empty value, no empty value allowed!
                if (Engine.checkNullValue(edit_name.getText().toString())) {
                    Engine.setCharacterSurname(edit_name.getText().toString());
                    text_fullname.setText(Engine.getCharacterFullname());
                }
            }
        });

        edit_legacy.addTextChangedListener(new TextWatcher() {

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            public void afterTextChanged(Editable s) {
                // Legacy is optional!!
                Engine.setCharacterLastname(edit_legacy.getText().toString());
                text_fullname.setText(Engine.getCharacterFullname());
            }
        });

        edit_background.addTextChangedListener(new TextWatcher() {

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            public void afterTextChanged(Editable s) {
                Engine.setCharacterBackground(Html.toHtml(edit_background.getText()));
            }
        });

        edit_background.setCustomSelectionActionModeCallback(new ActionMode.Callback() {

            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
//                menu.clear();
                MenuInflater inflater = mode.getMenuInflater();
                inflater.inflate(R.menu.text_edit, menu);
                return true;
            }

            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                Spannable str = edit_background.getText();
                int start = edit_background.getSelectionStart();
                int end = edit_background.getSelectionEnd();
                if (str != null) {
                    switch (item.getItemId()) {
                        case R.id.menu_font_bold:
                            str.setSpan(new StyleSpan(Typeface.BOLD), start, end, 0);
                            break;
                        case R.id.menu_font_italic:
                            str.setSpan(new StyleSpan(Typeface.ITALIC), start, end, 0);
                            break;
                        case R.id.menu_font_normal:
                            str.setSpan(new StyleSpan(Typeface.NORMAL), start, end, 0);
                            break;
                        default:
                            return false;
                    }
                    edit_background.setText(str);
                }
                return true;
            }

            public void onDestroyActionMode(ActionMode mode) {
            }
        });
    }

    private void initSpinner() {
        // Race Spinner
        raceSpinner.setAdapter(raceAdapter);
        if (!Engine.getCharacterRace().equals("")) {
            raceSpinner.setSelection(raceAdapter.getPosition(Engine.getCharacterRace()), true);
        }
        raceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Engine.setCharacterRace(raceAdapter.getItem(position).getData());
            }

            public void onNothingSelected(AdapterView<?> parent) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        });

        // Faction Spinner
        factionSpinner.setAdapter(factionAdapter);
        if (!Engine.getCharacterFaction().equals(de.tordroid.model.Faction.None)) {
            factionSpinner.setSelection(factionAdapter.getPosition(Engine.getCharacterFaction().toString()), true);
        }
        factionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Engine.setCharacterFaction(Faction.valueOf(factionAdapter.getItem(position).getData()));
                classSpinner.setAdapter(new IconSpinnerAdapter(Engine.getClasses(Engine.getCharacterFaction()), getActivity()));
            }

            public void onNothingSelected(AdapterView<?> parent) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        });

        // CharacterClass Spinner
        classSpinner.setAdapter(classAdapter);
        if (!Engine.getCharacterClass().equals(new CharacterClass())) {
            classSpinner.setSelection(classAdapter.getPosition(Engine.getCharacterClass()), true);
        }
        classSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (classAdapter.getCount() > 0) {
                    Engine.setCharacterClass(classAdapter.getItem(position).getData());
                }
            }

            public void onNothingSelected(AdapterView<?> parent) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.character_fragment, container, false);
        return view;
    }
}
